package com.ict.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ict.common.constant.UserConstants;
import com.ict.common.core.domain.entity.SysDept;
import com.ict.common.core.domain.entity.SysRole;
import com.ict.common.core.domain.entity.SysUser;
import com.ict.common.utils.SecurityUtils;
import com.ict.common.utils.StringUtils;
import com.ict.common.utils.uuid.IdUtils;
import com.ict.system.domain.SysUserRole;
import com.ict.system.mapper.SysUserMapper;
import com.ict.system.mapper.SysUserRoleMapper;
import com.ict.system.service.ISysDeptService;
import com.ict.system.service.ISysUserService;
import com.ict.web.constant.Constants;
import com.ict.web.domain.OrganizationManagement;
import com.ict.web.dto.InsertOrganizationManagementDto;
import com.ict.web.dto.QueryOrganizationManagementDto;
import com.ict.web.dto.UpdateOrganizationManagementDto;
import com.ict.web.mapper.OrganizationManagementMapper;
import com.ict.web.service.IOrganizationManagementService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 机构管理信息Service业务层处理
 *
 * @author liujie
 * @date 2022-02-18
 */
@Service
public class OrganizationManagementServiceImpl extends ServiceImpl<OrganizationManagementMapper,
        OrganizationManagement> implements IOrganizationManagementService {
    @Resource
    private OrganizationManagementMapper organizationManagementMapper;
    @Resource
    private ISysDeptService deptService;
    @Resource
    private ISysUserService userService;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    /**
     * 查询机构管理信息
     *
     * @param ormId 机构管理信息ID
     * @return 机构管理信息
     */
    @Override
    public OrganizationManagement selectOrganizationManagementByOrmId(Long ormId) {
        return organizationManagementMapper.selectOrganizationManagementByOrmId(ormId);
    }

    /**
     * 查询机构管理信息列表
     *
     * @param queryDto 机构管理信息
     * @return 机构管理信息
     */
    @Override
    public List<OrganizationManagement> selectOrganizationManagementList(QueryOrganizationManagementDto queryDto) {
        return organizationManagementMapper.selectOrganizationManagementList(queryDto);
    }

    /**
     * 新增机构管理信息
     *
     * @param dto 机构管理信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertOrganizationManagement(InsertOrganizationManagementDto dto) throws Exception {
        OrganizationManagement bean = InsertOrganizationManagementDto.of(dto);
        //名称重复性校验
        QueryWrapper<OrganizationManagement> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("organization_name", dto.getOrganizationName());
        queryWrapper.eq("is_delete", Constants.DELETE_STATUS_NORMAL);
        List<OrganizationManagement> list = organizationManagementMapper.selectList(queryWrapper);
        Assert.isTrue(list.size() == 0, "机构管理信息名称重复");
        //对应机构部门
        List<SysDept> sysDepts = deptService.selectDeptList(new SysDept(102L));
        Integer maxOrderNum = null;
        if(StringUtils.isNotEmpty(sysDepts)){
            List<String> collect = sysDepts.stream().map(SysDept::getOrderNum).collect(Collectors.toList());
             maxOrderNum = Integer.parseInt(Collections.max(collect))+1;
        }else {
            maxOrderNum=3;
        }
        SysDept sysDept = new SysDept();
        sysDept.setDeptId(IdUtils.snowId());
        sysDept.setDelFlag(Constants.DELETE_STATUS_NORMAL);
        sysDept.setParentId(102L);
        sysDept.setLeader(dto.getContacts());
        sysDept.setDeptName(dto.getOrganizationName());
        sysDept.setPhone(dto.getContactNumber());
        sysDept.setStatus(SysDept.STATUS_NORMAL);
        sysDept.setOrderNum(String.valueOf(maxOrderNum));
        deptService.insertDept(sysDept);

        //为主旨关联部门id
        List<SysDept> deptList = deptService.selectLastDept();
        if (!deptList.isEmpty()) {
            bean.setDeptId(deptList.get(0).getDeptId());
        }

        int result = organizationManagementMapper.insert(bean);
        Assert.isTrue(result > 0, "关联部门失败!!!");
        //只能在大数据区才能绑定三方账号
        List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
        List<Long> collect = roles.stream().map(SysRole::getRoleId).collect(Collectors.toList());
        Assert.isTrue(collect.contains(Constants.ROLE_TYPE_BIGDATA),
                "账号不是区大数据，请更换账号登录!!!");
        SysUser sysUser = new SysUser();
        sysUser.setDeptId(deptList.get(0).getDeptId());
        //设置默认密码test123
        sysUser.setPassword(SecurityUtils.encryptPassword("test123"));
        sysUser.setSex("2");
        sysUser.setDelFlag("0");
        sysUser.setEmail(LocalDateTime.now() + "@qq.com");
        sysUser.setUserType("2");
        sysUser.setUserName(dto.getContactNumber());
        sysUser.setNickName(dto.getOrganizationName());
        sysUser.setRemark("三方机构");
        sysUser.setPhonenumber(sysDept.getPhone());
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(sysUser.getUserName()))) {
            throw new Exception("新增用户'" + sysUser.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(sysUser.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(sysUser))) {
            throw new Exception("新增用户'" + sysUser.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(sysUser.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(sysUser))) {
            throw new Exception("新增用户'" + sysUser.getUserName() + "'失败，邮箱账号已存在");
        }
        userService.insertUser(sysUser);
        //增加用户与角色关系
        List<SysUserRole> userRoleList= new ArrayList<>();
        userRoleList.add(new SysUserRole(sysUser.getUserId(),104L));
        sysUserRoleMapper.batchUserRole(userRoleList);
        return result;
    }

    /**
     * 修改机构管理信息
     *
     * @param dto 机构管理信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateOrganizationManagement(UpdateOrganizationManagementDto dto) {
        OrganizationManagement organizationManagement = organizationManagementMapper.selectById(dto.getOrmId());
        OrganizationManagement bean = UpdateOrganizationManagementDto.of(dto);
        if (!dto.getOrganizationName().equals(organizationManagement.getOrganizationName())) {
            QueryWrapper<OrganizationManagement> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("organization_name", dto.getOrganizationName());
            queryWrapper.eq("is_delete", Constants.DELETE_STATUS_NORMAL);
            List<OrganizationManagement> list = organizationManagementMapper.selectList(queryWrapper);
            Assert.isTrue(list.size() == 0, "机构名称重复");
            //修改机构名字同步修改该机构对应的部门名字
            Assert.isTrue(StringUtils.isNotNull(bean.getDeptId()), "未找到该机构的部门信息，不能修改机构名称");
            SysDept dept = deptService.selectDeptById(bean.getDeptId());
            dept.setDeptName(bean.getOrganizationName());
            dept.setPhone(bean.getContactNumber());
            deptService.updateDept(dept);
        }
        if (!dto.getContactNumber().equals(organizationManagement.getContactNumber())) {
            //同步机构部门下用户的联系电话为机构的电话
            SysUser user = new SysUser();
            user.setDeptId(bean.getDeptId());
            List<SysUser> sysUsers = userService.selectUserList(user);
            sysUsers.stream().forEach(s->{
                s.setPhonenumber(bean.getContactNumber());
                s.setRoleIds(new Long[]{104L});
                s.setUserType("2");
                userService.updateUser(s);
            });
        }
        return organizationManagementMapper.updateById(bean);
    }

    /**
     * 删除机构管理信息信息
     *
     * @param ormId 机构管理信息ID
     * @return 结果
     */
    @Override
    public int deleteOrganizationManagementByOrmId(Long ormId) {
        OrganizationManagement bean = organizationManagementMapper.selectById(ormId);
        bean.setIsDelete("1");
        return organizationManagementMapper.updateById(bean);
    }
}
